//
//  RegisterOneStepViewController.m
//  MIT-AffordSuperMarket
//
//  Created by apple on 15/11/10.
//  Copyright © 2015年 河南大实惠电子商务有限公司. All rights reserved.
//

#import "RegisterOneStepViewController.h"
#define kleftSpace 10
#define kHSpace 16
#define kVSpace 22
//vendor
#import "TPKeyboardAvoidingScrollView.h"
#import "SaveDataInKeychain.h"
#import "RDVTabBarController.h"
//untils
#import "UIColor+Hex.h"
#import "UITextField+Space.h"
#import "Global.h"
#import "ManagerGlobeUntil.h"
#import "ManagerHttpBase.h"
#import "NSString+Conversion.h"
#import "VerificationPhoneNumber.h"
#import "AppDelegate.h"
//controllers
#import "Login_Controller.h"
#import "RegisterTwoStepViewController.h"
@interface RegisterOneStepViewController ()
@property(nonatomic, strong)TPKeyboardAvoidingScrollView *rootScrollView;
@property(nonatomic, strong)UITextField *phoneTextField;
@property(nonatomic, strong)UITextField *passwordTextField;
@property(nonatomic, strong)UIButton *checkCodeBtn;
@property(nonatomic, strong)UIButton *hadAccountBtn;
@property(nonatomic, strong)NSString *phoneCheckCode;//手机验证码
@end

@implementation RegisterOneStepViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithHexString:@"#efeeee"];
    [self addBackNavItem];
    [self setupSubView];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    AppDelegate *appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
    [appDelegate.tabBarController setTabBarHidden:YES animated:NO];
    [self changeNavgationItemTitle];
    [self changeSubViewStyle];
    [self isHideHadAccountButton];
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    AppDelegate *appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
    [appDelegate.tabBarController setTabBarHidden:NO animated:YES];
}
#pragma mark -- request Data
- (void)loadCheckCodeRequest

{
    /*
     SIGNATURE	加密签名
     PHONE	手机号码
     */
    
    //请求参数说明： SIGNATURE  设备识别码
    //      STOREID     商品ID
    NSString *portUrl = @"";
    if (self.typeOfView == OneStepIsRegister) {
        portUrl = @"user/sendRegCode";
    } else if (self.typeOfView == OneStepIsModifiedPassword || self.typeOfView == OneStepIsFindTheSecret) {
        portUrl = @"user/sendResetPwdCode";
    }
    ManagerHttpBase *manager = [ManagerHttpBase sharedManager];
    NSMutableDictionary *parameter = [[NSMutableDictionary alloc]init];
    [parameter setObject:self.phoneTextField.text forKey:@"PHONE"];
    __weak typeof(self)weakSelf = self;
    [manager parameters:parameter customPOST:portUrl success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            NSDictionary *dataDic = (NSDictionary*)responseObject;
            NSString *msg = [dataDic objectForKey:@"MSG"];
            NSString *state = [NSString stringTransformObject:[dataDic objectForKey:@"STATE"]];//状态码
            if ([state isEqualToString:@"0"]) {//请求成功
                /// self.phoneCheckCode = [[dataDic objectForKey:@"OBJECT"] objectForKey:@"CODE"];
                [weakSelf getcheckCodeSuccess];
            }else {//请求失败
                [[ManagerGlobeUntil sharedManager]showTextHUDWithMsg:msg inView:weakSelf.view];
            }
        }
        
        
    } failure:^(bool isFailure) {
        
        
    }];
    
}

- (void)loadUserModifiedOrFindPasswordCheckCodeRequest {
    
}

- (void)getcheckCodeSuccess
{
    RegisterTwoStepViewController *registerVC = [[RegisterTwoStepViewController alloc]init];
    registerVC.phoneNum = self.phoneTextField.text.length != 0 ? self.phoneTextField.text : @"";
    registerVC.checkCode = self.phoneCheckCode.length != 0 ? self.phoneCheckCode : @"";
    switch (self.typeOfView)
    {
        case OneStepIsRegister://注册
        {
            registerVC.typeOfView = twoStepIsRegister;
            [self.navigationController pushViewController:registerVC animated:YES];
        }
            break;
        case OneStepIsModifiedPassword://修改密码
        {
            registerVC.typeOfView = twoStepIsModifiedPassword;
            [self.navigationController pushViewController:registerVC animated:YES];
        }
            break;
        case OneStepIsFindTheSecret://找回密码
        {
            registerVC.typeOfView = twoStepIsFindTheSecret;
            [self.navigationController pushViewController:registerVC animated:YES];
        }
            break;
            
        default:
            break;
    }
    
}
- (void)loadModifiedPhoneNumberRequest
{
    /*
     ADAPTER	业务适配器
     SIGNATURE	加密签名
     PHONE	手机号码
     PASSWORD 密码
     */
    [self modifiedPhoneNumberRequestSuccess];
    [self hideKeyboard];
    
}

- (void)modifiedPhoneNumberRequestSuccess
{
    RegisterTwoStepViewController *registerVC = [[RegisterTwoStepViewController alloc]init];
    registerVC.typeOfView = TwoStepIsModifiedPhoneNumber;
    registerVC.phoneNum = self.phoneTextField.text.length != 0 ? self.phoneTextField.text : @"";
    registerVC.oldPassword = self.passwordTextField.text.length != 0 ? self.passwordTextField.text : @"";
    [self.navigationController pushViewController:registerVC animated:YES];
}
//点击获取验证码之前的判断
- (BOOL)phoneNumberIsRight{
    return [VerificationPhoneNumber isMobileNumber:self.phoneTextField.text];
}

#pragma mark -- button Action
//获取验证码事件
- (void)getCheckCodeEvent:(id)sender {
    [self hideKeyboard];
    switch (self.typeOfView)
    {
        case OneStepIsRegister://注册2页面
            if ([self phoneNumberIsRight])
            {
                [self loadCheckCodeRequest];
                
            } else {
                [[ManagerGlobeUntil sharedManager]showTextHUDWithMsg:@"手机号格式不正确" inView:self.view];
            }
            break;
        case OneStepIsModifiedPassword://修改密码2页面
            if ([self phoneNumberIsRight])
            {
                [self loadCheckCodeRequest];
            }else {
                [[ManagerGlobeUntil sharedManager]showTextHUDWithMsg:@"手机号格式不正确" inView:self.view];
            }
            break;
        case OneStepIsFindTheSecret://找回密码2页面
            if ([self phoneNumberIsRight])
            {
                [self loadCheckCodeRequest];
            }else {
                [[ManagerGlobeUntil sharedManager]showTextHUDWithMsg:@"手机号格式不正确" inView:self.view];
            }
            break;
        case OneStepIsModifiedPhoneNum://修改手机号2页面
            if ([self phoneNumberIsRight])
            {
                [self loadModifiedPhoneNumberRequest];
            }
            break;
        default:
            break;
    }

}
//已有账号事件
- (void)hadAccountEvent:(id)sender {
    //先判断栈里面是否有登陆页面，如果有直接跳转，如果没有生产登录对象跳转
    for (UIViewController *viewController in self.navigationController.childViewControllers) {
        if ([viewController isKindOfClass:[Login_Controller class]]) {
            [self.navigationController popToViewController:viewController animated:YES];
            return ;
        }
    }
    Login_Controller *loginVC = [[Login_Controller alloc]init];
    [self.navigationController pushViewController:loginVC animated:YES];
}
- (void)backBtnAction:(id)sender {
    [self.navigationController popToRootViewControllerAnimated:YES];
    
}

- (void)hideKeyboard
{
    if ([self.passwordTextField isFirstResponder])
    {
        [self.passwordTextField resignFirstResponder];
        
    }
    if ([self.phoneTextField isFirstResponder])
    {
        [self.phoneTextField resignFirstResponder];
    }
}

#pragma mark -- setup Subview
//根据视图类型来是否隐藏控件
- (void)isHideHadAccountButton
{
    switch (self.typeOfView) {
        case OneStepIsRegister://注册第一步按钮不隐藏
            self.hadAccountBtn.hidden = NO;
            self.passwordTextField.hidden = YES;
            self.phoneTextField.placeholder = @"输入手机号码";
            [self.checkCodeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
            [self changeSubViewFrame];
            break;
        case OneStepIsModifiedPassword://修改密码第一步按钮隐藏
            self.hadAccountBtn.hidden = YES;
            self.passwordTextField.hidden = YES;
            self.phoneTextField.placeholder = @"输入手机号码";
            [self.checkCodeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
            [self changeSubViewFrame];
            break;
        case OneStepIsFindTheSecret://找回密码第一步按钮隐藏
            self.hadAccountBtn.hidden = YES;
            self.passwordTextField.hidden = YES;
            self.phoneTextField.placeholder = @"输入手机号码";
            [self.checkCodeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
            [self changeSubViewFrame];
            break;
        case OneStepIsModifiedPhoneNum://变更手机号
            self.hadAccountBtn.hidden = YES;
            self.passwordTextField.hidden = NO;
            [self.checkCodeBtn setTitle:@"下一步" forState:UIControlStateNormal];
            self.phoneTextField.placeholder = @"输入原手机号码";
            [self recoverSubViewFrame];
            break;
            
        default:
            break;
    }
}

//修改子视图frame
- (void)changeSubViewFrame//修改密码或注册
{
    //按钮frame
    CGFloat y = CGRectGetMaxY(self.phoneTextField.frame) + kVSpace ;
    CGRect frame = CGRectMake(CGRectGetMinX(self.checkCodeBtn.frame), y, CGRectGetWidth(self.checkCodeBtn.frame), CGRectGetHeight(self.checkCodeBtn.frame));
    self.checkCodeBtn.frame = frame;
    //已有账号按钮frame
    CGRect rect = CGRectMake(CGRectGetMinX(self.hadAccountBtn.frame),CGRectGetMaxY(self.checkCodeBtn.frame)+4 , CGRectGetWidth(self.hadAccountBtn.frame), CGRectGetHeight(self.hadAccountBtn.frame));
    self.hadAccountBtn.frame = rect;
    
}

- (void)recoverSubViewFrame//变更手机号
{
    CGRect frame = CGRectMake(CGRectGetMinX(self.checkCodeBtn.frame), CGRectGetMaxY(self.passwordTextField.frame) + kVSpace, CGRectGetWidth(self.checkCodeBtn.frame), CGRectGetHeight(self.checkCodeBtn.frame));
    self.checkCodeBtn.frame = frame;
}

//改变子视图样式
- (void)changeSubViewStyle {
    if (self.typeOfView == OneStepIsModifiedPassword) {
        self.phoneTextField.enabled = NO;
        UserInfoModel *model = [[ManagerGlobeUntil sharedManager] getUserInfo];
        NSString * phoneStr = model.userName;
        if ([phoneStr length] != 0){
            self.phoneTextField.text = phoneStr;
        }
    } else {
        self.phoneTextField.enabled = YES;
    }
}
//设置标题
- (void)changeNavgationItemTitle {
    NSString * title;
    switch (self.typeOfView)
    {
        case 0:
            title = @"新用户注册";
            break;
        case 1:
            title = @"密码重置";
            break;
        case 2:
            title = @"密码找回";
            break;
        case 3:
            title = @"变更手机号码";
            break;
            
        default:
            break;
    }
    self.title = title;
}

- (void)setupSubView {
    
    UIImage *textfieldBackgroundImage = [UIImage imageNamed:@"intPutBg"];
    textfieldBackgroundImage = [textfieldBackgroundImage stretchableImageWithLeftCapWidth:6 topCapHeight:6];
    //根视图容器
    _rootScrollView = [[TPKeyboardAvoidingScrollView alloc]initWithFrame:CGRectMake(0
                                                                                    , 0
                                                                                    , CGRectGetWidth(self.view.bounds)
                                                                                    , CGRectGetHeight(self.view.bounds))];
    _rootScrollView.scrollViewDelegate = (id<TPKeyboardAvoidingScrollViewDelegate>)self;
    _rootScrollView.showsHorizontalScrollIndicator = NO;
    _rootScrollView.showsVerticalScrollIndicator = NO;
    _rootScrollView.backgroundColor = [UIColor clearColor];
    _rootScrollView.contentSize = CGSizeMake(CGRectGetWidth(self.view.bounds)
                                             , CGRectGetHeight(self.view.bounds) - 64);
    [self.view addSubview:_rootScrollView];
    //头部指示图片
    UIImageView *leftImageView = [[UIImageView alloc]initWithFrame:CGRectMake(kleftSpace
                                                                             , 15
                                                                             , (CGRectGetWidth(self.view.bounds) - 2*kleftSpace - kHSpace)/2
                                                                             , 3)];
    leftImageView.image = [UIImage imageNamed:@"blue_line"];
    leftImageView.hidden = YES;
    [_rootScrollView addSubview:leftImageView];
    
    UIImageView *rightImageView = [[UIImageView alloc]initWithFrame:CGRectMake(CGRectGetMaxX(leftImageView.frame) + kHSpace
                                                                              , CGRectGetMinY(leftImageView.frame)
                                                                              , CGRectGetWidth(leftImageView.bounds)
                                                                               , CGRectGetHeight(leftImageView.bounds))];
    rightImageView.image = [UIImage imageNamed:@"gray_line"];
    rightImageView.hidden = YES;
    [_rootScrollView addSubview:rightImageView];
    //手机号文本框
    _phoneTextField = [[UITextField alloc]initWithFrame:CGRectMake(CGRectGetMinX(leftImageView.frame)
                                                                  ,CGRectGetMaxY(leftImageView.frame) + kVSpace - 15
                                                                  ,CGRectGetWidth(self.view.bounds) - 2*kleftSpace
                                                                   , 44)];
    _phoneTextField.font = [UIFont systemFontOfSize:16];
    _phoneTextField.background = textfieldBackgroundImage;
    _phoneTextField.placeholder = @"输入手机号码";
    [_phoneTextField setDirection:kLeftEdge edgeSpace:8];
    [_rootScrollView addSubview:_phoneTextField];
    //密码输入框
    _passwordTextField = [[UITextField alloc]initWithFrame:CGRectMake(CGRectGetMinX(_phoneTextField.frame)
                                                                     , CGRectGetMaxY(_phoneTextField.frame) + kVSpace
                                                                     , CGRectGetWidth(_phoneTextField.bounds)
                                                                      , CGRectGetHeight(_phoneTextField.bounds))];
    _passwordTextField.font = [UIFont systemFontOfSize:16];
    _passwordTextField.placeholder = @"输入密码";
    _passwordTextField.background = textfieldBackgroundImage;
    [_passwordTextField setDirection:kLeftEdge edgeSpace:8];
    [_rootScrollView addSubview:_passwordTextField];
    
    //获取验证码按钮
    _checkCodeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _checkCodeBtn.frame = CGRectMake(CGRectGetMinX(_passwordTextField.frame)
                                     , CGRectGetMaxY(_passwordTextField.frame) + kVSpace
                                     , CGRectGetWidth(_passwordTextField.bounds)
                                     , CGRectGetHeight(_passwordTextField.bounds));
    [_checkCodeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
    UIImage *loginImage = [UIImage imageNamed:@"login_Btn"];
    loginImage = [loginImage stretchableImageWithLeftCapWidth:6 topCapHeight:6];
    [_checkCodeBtn setBackgroundImage:loginImage forState:UIControlStateNormal];
    [_checkCodeBtn addTarget:self action:@selector(getCheckCodeEvent:) forControlEvents:UIControlEventTouchUpInside];
    [_rootScrollView addSubview:_checkCodeBtn];
    //已有账号按钮
    _hadAccountBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _hadAccountBtn.frame = CGRectMake(CGRectGetWidth(self.view.bounds) - 140
                                          , CGRectGetMaxY(_checkCodeBtn.frame) + 4
                                          , 125, 44);
    [_hadAccountBtn setTitle:@"已有账号?" forState:UIControlStateNormal];
    _hadAccountBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [_hadAccountBtn setTitleColor:[UIColor colorWithHexString:@"#72706f"] forState:UIControlStateNormal];
    _hadAccountBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    _hadAccountBtn.backgroundColor = [UIColor clearColor];
    [_hadAccountBtn addTarget:self action:@selector(hadAccountEvent:) forControlEvents:UIControlEventTouchUpInside];
    [_rootScrollView addSubview:_hadAccountBtn];
    
    
   
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
